<?php
namespace Application\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\ResultSet\ResultSet;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
class ImageTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }
    public function getImagebyId($id) {
    	$id = ( int ) $id;
    	$rowset = $this->tableGateway->select ( array (
    			'id' => $id
    	) );
    	$row = $rowset->current ();
    	if (! $row) {
    		throw new \Exception ( "Could not find row option $id" );
    	}
    	return $row;
    }
    public function fetchAll($paginated=false)
    {
        if($paginated) {
        	// create a new Select object for the table album
        	$select = new Select('image');
        	// create a new result set based on the Album entity
        	$resultSetPrototype = new ResultSet();
        	$resultSetPrototype->setArrayObjectPrototype(new Product());
        	// create a new pagination adapter object
        	$paginatorAdapter = new DbSelect(
        			// our configured select object
        			$select,
        			// the adapter to run it against
        			$this->tableGateway->getAdapter(),
        			// the result set to hydrate
        			$resultSetPrototype
        	);
        	$paginator = new Paginator($paginatorAdapter);
        	return $paginator;
        }
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function saveImage(Image $image) {
    	$data = array(
    			'product_id' => $image->product_id,
    			'name'  => $image->name,
    			'content'  => $image->content,
    			'type'  => $image->type,
    			'size'  => $image->size,

    	);

    	$id = (int)$image->id;

    	if ($id == 0) {
    		$this->tableGateway->insert($data);
    	} else {
    		if ($this->getProductbyId($id)) {
    			$this->tableGateway->update($data, array('id' => $id));
    		} else {
    			throw new \Exception('Form id does not exist');
    		}
    	}
    }
    public function deleteImage($id)
    {
    	return $this->tableGateway->delete(array('id' => $id));
    }
    public function getImageByProductId($productID){
       return  $this->tableGateway->select(array("product_id"=>$productID));
    }
}